#include <memory>
#include <iostream>
using namespace std;

void Check(weak_ptr<int>& wp) {
    shared_ptr<int> sp = wp.lock(); // 转换为share_ptr<int>
    if (sp != nullptr) {
        cout << "Still: " << *sp << endl;
    } else {
        cout << "pointer is invalid" << endl;
    }
}

int main(int argc, char* argv[])
{
    // unique_ptr [[
    unique_ptr<int> upi1(new int(11));
    std::cout << "unique_ptr test 1:" << *upi1 << std::endl;
    unique_ptr<int> upi2 = move(upi1); // 转移所有权

    // std::cout << "unique_ptr test 2:" << *upi1 << std::endl; // 会运行错误
    std::cout << "unique_ptr test 3:" << *upi2 << std::endl;

    upi1.reset();
    upi2.reset();
    // ]]

    // shared_ptr [[
    shared_ptr<int> sp1(new int(12)); // 引用计数为1
    shared_ptr<int> sp2(sp1); // 引用计数为2
    std::cout << "shared_ptr test 1:" << *sp1 << std::endl;
    std::cout << "shared_ptr test 2:" << *sp2 << std::endl;
    sp1.reset();
    std::cout << "shared_ptr test 1:" << *sp2 << std::endl;
    // ]]

    // weak_ptr [[
    shared_ptr<int> sp3(new int(44));
    shared_ptr<int> sp4 = sp3;
    weak_ptr<int>   wp1 = sp3; // 指向shared_ptr对象
    std::cout << "weak_ptr test 1:" << *sp3 << std::endl;
    std::cout << "weak_ptr test 2:" << *sp4 << std::endl;
    Check(wp1);

    sp3.reset();
    // std::cout << "weak_ptr test reset() 3:" << *sp3 << std::endl; // 运行错误
    Check(wp1);

    sp4.reset();
    Check(wp1);
    // ]]

    return (0);
}
